import React, { useState } from 'react';
import { Card, Form, Input, Button, message, Row, Col } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, PhoneOutlined, UserAddOutlined } from '@ant-design/icons';
import { Navigate } from 'react-router-dom';
import request from '../../../utils/request.jsx';
import './index.css';

const RegisterPage = () => {
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [isRegistered, setIsRegistered] = useState(false);
  const [showLogin, setShowLogin] = useState(false);
  
  // 如果注册成功，显示登录提示
  if (isRegistered) {
    return (
      <div className="register-container">
        <Row justify="center" align="middle" className="login-row">
          <Col xs={24} sm={20} md={12} lg={8} xl={6}>
            <Card title="注册成功" className="login-card">
              <div className="register-success">
                <p>您的账户已成功注册，默认角色为普通用户。</p>
                <p>请点击下方按钮返回登录页面。</p>
                <Button 
                  type="primary" 
                  onClick={() => setShowLogin(true)}
                  className="mt-4"
                  block
                >
                  去登录
                </Button>
              </div>
            </Card>
          </Col>
        </Row>
        {showLogin && <Navigate to="/login" replace />}
      </div>
    );
  }
  
  // 处理注册表单提交
  const handleSubmit = async (values) => {
    try {
      setLoading(true);
      // 注册用户默认为普通用户角色
      const registerData = {
        ...values,
        role: 'user' // 明确设置角色为user
      };
      const response = await request.post('/auth-center/auth/register', registerData);
      if (response.code === 200) {
        message.success('注册成功');
        setIsRegistered(true);
        // 注册成功后重置表单
        form.resetFields();
      } else {
        message.error(response.message || '注册失败');
      }
    } catch (error) {
      message.error('注册失败，请检查网络或稍后重试');
      console.error('注册错误:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="register-container">
      <Row justify="center" align="middle" className="login-row">
        <Col xs={24} sm={20} md={12} lg={8} xl={6}>
          <Card title="API管理平台注册" className="login-card">
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
            >
              <Form.Item
                name="username"
                label="用户名"
                rules={[
                  { required: true, message: '请输入用户名' },
                  { whitespace: true, message: '用户名不能包含空格' },
                  { pattern: /^[a-zA-Z0-9_]{3,20}$/, message: '用户名只能包含字母、数字和下划线，长度为3-20位' }
                ]}
                hasFeedback
              >
                <Input
                  prefix={<UserOutlined className="site-form-item-icon" />}
                  placeholder="请输入用户名"
                  autoComplete="username"
                />
              </Form.Item>
              
              <Form.Item
                name="password"
                label="密码"
                rules={[
                  { required: true, message: '请输入密码' },
                  { pattern: /^[a-zA-Z0-9_]{6,20}$/, message: '密码只能包含字母、数字和下划线，长度为6-20位' }
                ]}
                hasFeedback
              >
                <Input
                  prefix={<LockOutlined className="site-form-item-icon" />}
                  type="password"
                  placeholder="请输入密码"
                  autoComplete="new-password"
                />
              </Form.Item>
              
              <Form.Item
                name="confirmPassword"
                label="确认密码"
                dependencies={['password']}
                rules={[
                  { required: true, message: '请确认密码' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不一致'));
                    },
                  }),
                ]}
                hasFeedback
              >
                <Input
                  prefix={<LockOutlined className="site-form-item-icon" />}
                  type="password"
                  placeholder="请再次输入密码"
                  autoComplete="new-password"
                />
              </Form.Item>
              
              <Form.Item
                name="nickname"
                label="昵称"
                rules={[
                  { required: true, message: '请输入昵称' },
                  { whitespace: true, message: '昵称不能包含空格' }
                ]}
              >
                <Input
                  prefix={<UserOutlined className="site-form-item-icon" />}
                  placeholder="请输入昵称"
                />
              </Form.Item>
              
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' }
                ]}
                hasFeedback
              >
                <Input
                  prefix={<MailOutlined className="site-form-item-icon" />}
                  placeholder="请输入邮箱"
                  autoComplete="email"
                />
              </Form.Item>
              
              <Form.Item
                name="phone"
                label="手机号"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
                ]}
                hasFeedback
              >
                <Input
                  prefix={<PhoneOutlined className="site-form-item-icon" />}
                  placeholder="请输入手机号"
                  autoComplete="tel"
                />
              </Form.Item>
              
              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  className="login-button"
                  loading={loading}
                  block
                  icon={<UserAddOutlined />}
                >
                  注册
                </Button>
                <div className="login-link">
                  已有账号？ <Button type="link" onClick={() => setShowLogin(true)}>立即登录</Button>
                </div>
              </Form.Item>
            </Form>
          </Card>
        </Col>
      </Row>
      {showLogin && <Navigate to="/login" replace />}
    </div>
  );
};

export default RegisterPage;